import Utils

playableConfig = dict()
inited = False

def __init():
    global inited
    global playableConfig
    
    if inited:
        return
    inited = True

    playable_config_path = 'bin/playable.json'
    if not Utils.hasPath(playable_config_path):
        playableConfig = {
            "tiktok_sdk_url" : "https://sf16-muse-va.ibytedtos.com/obj/union-fe-nc-i18n/playable/sdk/playable-sdk.js"
        }
        Utils.writeDictInFile(playable_config_path,playableConfig)
    else:
        playableConfig = Utils.fromJsonAsDict(playable_config_path)


androidUrl = 'https://play.google.com/store/apps/details?id=com.hg.hexsnake'
iosUrl = 'https://apps.apple.com/app/id1438597314'
languages = ['zh', 'en', 'ja', 'ko', 'zhHant']
orientation = ['横竖均可', '竖屏', '横屏']

def __caseUnity():
    return Utils.JavaScript(
        'window.androidStoreUrl="%s";window.iosStoreUrl="%s";' % (androidUrl, iosUrl) +
        'window.hgPlayableSDK={},window.gameReady=function(){function a(a){a&&c()}function b(){mraid.addEventListener("viewableChange",a),mraid.isViewable()&&c()}function c(){window.cc&&cc.director.resume()}try{console.log(">>> game ready"),window.hgPlayableSDK.storeUrl=/android/i.test(navigator.userAgent)?window.androidStoreUrl:window.iosStoreUrl,"mraid"in window&&"loading"===mraid.getState()?(window.cc&&!cc.director.isPaused()&&cc.Game.pause(),mraid.addEventListener("ready",b)):b()}catch(d){console.log(">>> 请在指定平台运行")}},window.install=function(){console.log(">>> game install"),"mraid"in window&&window.mraid.open(window.hgPlayableSDK.storeUrl)};',False)

def __caseTiktok():
    sdk_url = playableConfig['tiktok_sdk_url']
    sdk = f'<script src = "{sdk_url}"></script>\n'
    sdk += Utils.JavaScript("window.install=function(){window.openAppStore&&window.openAppStore()};",False)
    return sdk

__caseHandle = {
    'unity': __caseUnity,
    'tiktok': __caseTiktok
}

#追加试玩渠道特性
def AppendPlayableProperty(x):
    __init()

    sdk = __caseHandle[x]()
    return sdk

# 输出试玩包体
def OutputPlayablePkt(dest,content,channel):

    root = f'{dest}/{channel}'
    name = 'index.html'

    # 创建渠道路径
    Utils.makePath( root )

    # 根据渠道特性 打包 压缩包 | 配置文件 | 单html
    if channel == "unity":
        Utils.writeInFile(f'{root}/{name}', content)
    elif channel == 'tiktok':
        config = {}
        config['playable_orientation'] = 0
        config['playable_languages'] = []
        config['playable_languages'].append(languages[0])

        Utils.writeDictInFile(f'{root}/config.json', config)
        Utils.writeInFile(f'{root}/{name}', content)
        # Utils.zipFiles(OutPath + name, OutPath + name + '.zip')
        # Utils.removeFile(OutPath + name)